using IQIGame.Onigao.Game;
using System;

namespace IQIGame.Onigao.Logic
{
    public struct FixedBVHBounds2D
    {
        public Vector2Logic min { get; private set; }
        public Vector2Logic max { get; private set; }

        public FixedBVHBounds2D(Vector2Logic min, Vector2Logic max)
        {
            this.min = min;
            this.max = max;
        }

        public static FixedBVHBounds2D FromRect(RectLogic rect)
        {
            return new FixedBVHBounds2D(rect.min, rect.max);
        }

        public static FixedBVHBounds2D FromPosSize(Vector2Logic pos, Vector2Logic size)
        {
            Vector2Logic halfSize = size / 2;
            Vector3Logic min = pos - halfSize;
            Vector3Logic max = pos + halfSize;
            return new FixedBVHBounds2D(min, max);
        }

        /// <summary>
        /// 获取包围盒矩形
        /// </summary>
        /// <param name="pos"></param>
        /// <param name="size"></param>
        /// <returns></returns>
        public static FixedBVHBounds2D FromPosSize(Vector3Logic pos, Vector3Logic size)
        {
            Vector3Logic halfSize = size / 2;
            Vector3Logic min = pos - halfSize;
            Vector3Logic max = pos + halfSize;
            return new FixedBVHBounds2D(new Vector2Logic(min.x, min.z), new Vector2Logic(max.x, max.z));
        }

        /// <summary>
        /// 获取旋转后的包围盒矩形的最小外包围矩形
        /// 返回的依然是不带旋转的矩形
        /// </summary>
        /// <param name="pos"></param>
        /// <param name="size"></param>
        /// <param name="yRotation"></param>
        /// <returns></returns>
        public static FixedBVHBounds2D FromPosSizeRotationY(Vector2Logic pos, Vector2Logic size, float yRotation)
        {
            Vector2Logic halfSize = size / 2;
            float rotationRad = yRotation * MathLogic.Deg2Rad;
            Vector2Logic axissX = new Vector2Logic((float)Math.Cos(rotationRad), -(float)Math.Sin(rotationRad));
            Vector2Logic axissZ = new Vector2Logic(-axissX.y, axissX.x);
            Vector2Logic axissXHalfSize = axissX * halfSize.x;
            Vector2Logic axissZHalfSize = axissZ * halfSize.y;
            Vector2Logic min = pos - axissXHalfSize - axissZHalfSize;
            Vector2Logic max = pos + axissXHalfSize + axissZHalfSize;
            return new FixedBVHBounds2D(Vector2Logic.Min(min, max), Vector2Logic.Max(min, max));
        }

        public bool Intersects(FixedBVHBounds2D other)
        {
            return !((max.x < other.min.x) || (min.x > other.max.x) ||
                   (max.y < other.min.y) || (min.y > other.max.y));
        }

        public bool Contains(Vector2Logic point)
        {
            return (point.x >= min.x) && (point.x <= max.x) &&
                   (point.y >= min.y) && (point.y <= max.y);
        }

        // 是否相等
        public bool IsEqual(FixedBVHBounds2D other)
        {
            return min == other.min && max == other.max;
        }
    }
}